<template>
  <div class="dic-manage-container">
    <v-row no-gutters class="dic-row">
      <!-- 字典表列表 -->
      <v-col cols="3" class="left-panel">
        <div class="panel-header">
          <span>字典表</span>
          <v-btn variant="text" color="grey" class="add-btn" @click="addDict">
            <v-icon>mdi-plus</v-icon> 新增
          </v-btn>
        </div>
        <v-list>
          <v-list-item
            v-for="dict in dictList"
            :key="dict.id"
            :active="dict.id === selectedDictId"
            @click="selectDict(dict.id)"
            class="dict-list-item"
          >
            <v-list-item-title>
              <div style="font-weight:bold;">{{ dict.name }}</div>
              <div style="font-size:12px;color:#888;">{{ dict.code }}</div>
            </v-list-item-title>
            <template #append>
              <v-btn variant="text" color="grey" class="delete-btn" @click.stop="deleteDict(dict.id)">
                <v-icon>mdi-delete</v-icon>
              </v-btn>
            </template>
          </v-list-item>
        </v-list>
        <v-progress-circular v-if="loading" indeterminate color="primary" size="32" class="mt-4 mx-auto" />
      </v-col>
      <!-- 字典项列表 -->
      <v-col cols="9" class="right-panel">
        <div class="panel-header">
          <span>字典项</span>
          <v-btn variant="text" color="grey" class="add-btn" @click="addItem" :disabled="!selectedDictId">
            <v-icon>mdi-plus</v-icon> 新增
          </v-btn>
        </div>
        <v-list>
          <v-list-item
            v-for="item in dictItems"
            :key="item.id || item.detailId"
            class="dict-item-list-item"
          >
            <v-list-item-title>{{ item.name || item.detailName }} ({{ item.code || item.detailValue }})</v-list-item-title>
            <template #append>
              <v-btn variant="text" color="grey" class="delete-btn" @click.stop="deleteItem(item.id || item.detailId)">
                <v-icon>mdi-delete</v-icon>
              </v-btn>
            </template>
          </v-list-item>
          <v-progress-circular v-if="itemsLoading" indeterminate color="primary" size="32" class="mt-4 mx-auto" />
          <div v-if="!itemsLoading && dictItems.length === 0" class="empty-tip">暂无字典项</div>
        </v-list>
      </v-col>
    </v-row>
    <!-- 新增字典表弹窗 -->
    <v-dialog v-model="showAddDialog" max-width="400px">
      <v-card>
        <v-card-title>新增字典表</v-card-title>
        <v-card-text>
          <v-form @submit.prevent="onAddDict">
            <v-text-field v-model="addForm.typeCode" label="字典类型编码" required />
            <v-text-field v-model="addForm.typeName" label="字典类型名称" required />
            <v-text-field v-model="addForm.remark" label="备注" />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showAddDialog = false">取消</v-btn>
          <v-btn color="primary" @click="onAddDict">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!-- 新增字典项弹窗 -->
    <v-dialog v-model="showAddItemDialog" max-width="400px">
      <v-card>
        <v-card-title>新增字典项</v-card-title>
        <v-card-text>
          <v-form @submit.prevent="onAddItem">
            <v-text-field v-model="addItemForm.code" label="字典项编码" required />
            <v-text-field v-model="addItemForm.name" label="字典项名称" required />
            <v-text-field v-model="addItemForm.sort" label="排序" type="number" />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showAddItemDialog = false">取消</v-btn>
          <v-btn color="primary" @click="onAddItem">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!-- 删除确认弹窗 -->
    <v-dialog v-model="showDeleteDialog" max-width="360">
      <v-card>
        <v-card-title class="text-h6">确认删除</v-card-title>
        <v-card-text>确定要删除{{ deleteType === 'dict' ? '该字典表' : '该字典项' }}吗？此操作不可恢复。</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="onDeleteCancel">取消</v-btn>
          <v-btn color="error" @click="onDeleteConfirm">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!-- 操作提示 -->
    <v-snackbar v-model="snackbar" :color="snackbarColor" timeout="2000" location="top">
      {{ snackbarText }}
    </v-snackbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getDictionaryTypeList, addDictionaryType, getDictionaryDetailList, addDictionaryDetail, deleteDictionaryDetail, deleteDictionaryType } from '@/api/resource'

// 字典表数据
const dictList = ref([])
const selectedDictId = ref(null)
const selectedDictCode = ref('')
const loading = ref(false)

// 字典项数据
const dictItems = ref([])
const itemsLoading = ref(false)

// 新增字典表弹窗
const showAddDialog = ref(false)
const addForm = ref({
  typeCode: '',
  typeName: '',
  status: 1,
  remark: '',
})

// 新增字典项弹窗
const showAddItemDialog = ref(false)
const addItemForm = ref({
  code: '',
  name: '',
  sort: 0
})

// Snackbar
const snackbar = ref(false)
const snackbarText = ref('')
const snackbarColor = ref('success')
function showSnackbar(text, color = 'success') {
  snackbarText.value = text
  snackbarColor.value = color
  snackbar.value = true
}

// 删除确认弹窗
const showDeleteDialog = ref(false)
const deleteType = ref('') // 'dict' or 'item'
const deleteId = ref(null)

function confirmDelete(type, id) {
  deleteType.value = type
  deleteId.value = id
  showDeleteDialog.value = true
}
function onDeleteConfirm() {
  if (deleteType.value === 'dict') {
    deleteDictionaryType(deleteId.value)
      .then(() => {
        showSnackbar('删除字典表成功', 'success')
        fetchDictList()
      })
      .catch(() => {
        showSnackbar('删除字典表失败', 'error')
      })
  } else if (deleteType.value === 'item') {
    deleteDictionaryDetail(deleteId.value)
      .then(() => {
        showSnackbar('删除字典项成功', 'success')
        fetchDictItems(selectedDictCode.value)
      })
      .catch(() => {
        showSnackbar('删除字典项失败', 'error')
      })
  }
  showDeleteDialog.value = false
}
function onDeleteCancel() {
  showDeleteDialog.value = false
}

// 获取字典表列表
function fetchDictList() {
  loading.value = true
  getDictionaryTypeList().then(res => {
    dictList.value = (res.data || []).map(item => ({
      id: item.id,
      name: item.typeName,
      code: item.typeCode,
      items: [] // 预留字典项
    }))
    if (!selectedDictId.value && dictList.value.length) {
      selectedDictId.value = dictList.value[0].id
      selectedDictCode.value = dictList.value[0].code
      fetchDictItems(dictList.value[0].code)
    }
  }).finally(() => {
    loading.value = false
  })
}

function fetchDictItems(typeCode) {
  if (!typeCode) {
    dictItems.value = []
    return
  }
  itemsLoading.value = true
  getDictionaryDetailList(typeCode).then(res => {
    dictItems.value = res.data || []
  }).finally(() => {
    itemsLoading.value = false
  })
}

onMounted(() => {
  fetchDictList()
})

function selectDict(id) {
  const dict = dictList.value.find(d => d.id === id)
  selectedDictId.value = id
  selectedDictCode.value = dict?.code || ''
  fetchDictItems(dict?.code)
}
function addDict() {
  addForm.value = { typeCode: '', typeName: '', status: 1, remark: '' }
  showAddDialog.value = true
}
async function onAddDict() {
  try {
    await addDictionaryType({
      id: '',
      ...addForm.value,
      createTime: '',
      updateTime: ''
    })
    showAddDialog.value = false
    fetchDictList()
    showSnackbar('新增字典表成功', 'success')
  } catch (e) {
    showSnackbar('新增失败', 'error')
  }
}
function addItem() {
  addItemForm.value = { code: '', name: '', sort: 0 }
  showAddItemDialog.value = true
}
async function onAddItem() {
  try {
    await addDictionaryDetail({
      id: '',
      dictCode: selectedDictCode.value,
      code: addItemForm.value.code,
      name: addItemForm.value.name,
      sort: addItemForm.value.sort
    })
    showAddItemDialog.value = false
    fetchDictItems(selectedDictCode.value)
    showSnackbar('新增字典项成功', 'success')
  } catch (e) {
    showSnackbar('新增字典项失败', 'error')
  }
}
function deleteDict(id) {
  if (!id) return
  confirmDelete('dict', id)
}
function deleteItem(itemId) {
  if (!itemId) return
  confirmDelete('item', itemId)
}
</script>

<style scoped>
.dic-manage-container {
  height: calc(100vh - 64px);
  background: var(--v-theme-surface, #f4f6fa);
  padding: 32px 0 0 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}
.dic-row {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  height: 80vh;
  min-height: 500px;
  display: flex;
}
.left-panel {
  background: var(--v-theme-background, #23272f);
  border-radius: 12px 0 0 12px;
  min-width: 220px;
  max-width: 260px;
  height: 100%;
  margin-left: 32px;
  margin-right: 0;
  box-shadow: 0 4px 16px 0 rgba(60,60,80,0.44), 0 1px 4px 0 #b0b0b7;
  border: 2px solid #444;
  display: flex;
  flex-direction: column;
  transition: box-shadow 0.2s;
}
.right-panel {
  background: var(--v-theme-surface, #fff);
  border-radius: 0 12px 12px 0;
  margin-left: 0;
  margin-right: 32px;
  height: 100%;
  box-shadow: 0 4px 16px 0 rgba(60,60,80,0.44), 0 1px 4px 0 #b0b0b7;
  border: 2px solid #444;
  border-left: none;
  display: flex;
  flex-direction: column;
  transition: box-shadow 0.2s;
  min-width: 0;
  flex: 1 1 0;
}
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 12px;
  padding: 16px 20px 0 20px;
  color: var(--v-theme-on-surface, #fff);
}
.add-btn, .delete-btn {
  background: rgba(128,128,128,0.08) !important;
  color: #666 !important;
  min-width: 0;
  padding: 0 8px;
  margin-left: 8px;
}
.dict-list-item {
  cursor: pointer;
  color: var(--v-theme-on-surface, #fff);
}
.dict-list-item.v-list-item--active {
  background: rgba(25, 118, 210, 0.18) !important;
  color: #1976d2 !important;
}
.dict-item-list-item {
  background: transparent !important;
}
.dict-item-list-item .v-list-item-title {
  margin-left: 24px;
}
.empty-tip {
  color: #aaa;
  text-align: center;
  padding: 32px 0;
}
</style>
